package flextv.main.logic.download {

import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.utils.Timer;

import flextv.core.download.IDownloadable;
import flextv.core.logic.Logger;
import flextv.core.vo.StoredItem;
import flextv.main.event.StoredItemDownloadedEvent;

import mx.logging.ILogger;

public class MockDownloadService implements IDownloadService {
	
	private static const LOG: ILogger = Logger.getLog(MockDownloadService);
	
	private static const DUMMY: File = new File("app:/dummy.flv");
	
	
	public function MockDownloadService() {
	}
	
	public function download(item: IDownloadable, target: File, fnFlvUriReady: Function): void {
		LOG.info("download(item="+item+"; target="+target+")");
		
		var t: Timer = new Timer(5, 50);
		t.addEventListener(TimerEvent.TIMER, function(event: TimerEvent): void {
			
			if(item.downloaded == 0 && fnFlvUriReady != null) {
				fnFlvUriReady(); // indicate flvUri is ready
			}
			
			if(item.downloaded == 98) {
				copyDummyFile(target);
			}
			
			item.downloaded += 2;
			
			if(item.downloaded == 100) {
				new StoredItemDownloadedEvent(item as StoredItem).dispatch(); // HACK static casting!
			}
		});
		t.start();
	}
	
	
	private static function copyDummyFile(target: File): void {
		if(DUMMY.exists == false) {
			throw new Error("Dummy FLV file does not exist at [" + DUMMY.nativePath + "]!");
		}
		
		DUMMY.copyTo(target, true);
	}
}
}